<template>
  <div id="tabs-view-container"
    class="tabs-view-container">
    <!-- 左移 -->
    <div class="tabs-control"
      @click="handleScrollPrev">
      <i class="el-icon-d-arrow-left"></i>
    </div>
    <!-- 路由标签显示区域（滚动）组件 -->
    <scroll-pane ref="scrollPane"
      class="tabs-view-wrapper">
      <!-- 路由标签 -->
      <router-link v-for="tab in visitedViews"
        ref="tab"
        :key="tab.path"
        :to="{ path: tab.path }"
        tab="span"
        class="tabs-view-item tabs-control"
        :class="{noPadding: tab.path === '/home', active: isActiveTab(tab) }">
        {{ tab.title }}
        <span v-if="tab.path !=='/home'"
          class="el-icon-close"
          @click.prevent.stop="closeSelectedTab(tab)" />
      </router-link>
    </scroll-pane>
    <!-- 右移 -->
    <div class="tabs-control"
      @click="handleScrollNext">
      <i class="el-icon-d-arrow-right"></i>
    </div>
    <!-- 关闭刷新下拉操作 -->
    <el-dropdown class="tabs-control">
      <div class="tabs-control">
        <i class="el-icon-arrow-down"></i>
      </div>
      <el-dropdown-menu slot="dropdown">
        <el-dropdown-item @click.native="refreshSelectedTab"><i class="el-icon-refresh"></i>刷新</el-dropdown-item>
        <!-- 只有首页时，只能刷新，否则首页可以刷新和关闭其他 -->
        <el-dropdown-item @click.native="closeOthersTabs"
          divided
          v-if="control()"><i class="el-icon-circle-close"></i>关闭其他</el-dropdown-item>
        <el-dropdown-item v-if="!isAffix(this.getCurrentTab())"
          @click.native="closeSelectedTab()"><i class="el-icon-circle-close"></i>关闭当前</el-dropdown-item>
        <el-dropdown-item @click.native="closeAllTabs"
          v-if="!isAffix(this.getCurrentTab())"><i class="el-icon-circle-close"></i>关闭所有</el-dropdown-item>
      </el-dropdown-menu>
    </el-dropdown>
  </div>
</template>

<script>
import { mapActions, mapState, mapMutations } from 'vuex';
import ScrollPane from './scrollPane';

export default {
  name: 'tabsView',
  components: { ScrollPane },
  data() {
    return {
      visitedViews: []
    };
  },
  computed: {
    ...mapState('tabsView', [
      'centerViews',
      'affixTabs',
      'defaultCenterId',
      'activeDate'
    ])
  },
  watch: {
    $route() {
      this.moveToCurrentTab();
    },
    centerViews: {
      handler() {
        this.visitedViewsChange();
      },
      immediate: true,
      deep: true,
    }
  },
  mounted() {
    this.initTabs()
  },
  methods: {
    ...mapActions('tabsView', ['addView', 'addCachedView', 'delView', 'delOthersViews', 'delAllViews', 'delCachedView']),
    ...mapMutations('tabsView', ['SET_ACTIVE_DATE']),
    visitedViewsChange() {
      this.visitedViews = this.centerViews[this.defaultCenterId].visitedViews;
    },
    // 左移操作
    handleScrollNext() {
      this.$refs.scrollPane.scrollNext();
    },
    // 右移操作
    handleScrollPrev() {
      this.$refs.scrollPane.scrollPrev();
    },
    // 判断当前 tab 是否在 affixTabs 中
    isAffix(tab) {
      return this.affixTabs.map(item => item.path).includes(tab.path);
    },
    control() {
      return this.visitedViews.length > 1 ? true : false
    },
    // 初始化标签栏 (首页固定)
    initTabs() {
      const { affixTabs } = this;
      affixTabs.forEach((tab) => {
        if (tab.path) {
          this.addView({ tab, centerId: this.defaultCenterId });
        }
      });
      if (this.$route.path !== '/home') {
        this.$router.replace('/home');
      }
    },
    // 刷新当前标签
    refreshSelectedTab() {
      const { meta, name, path } = this.$route;
      if (!name) {
        return;
      }
      this.delCachedView(name).then(() => {
        this.$nextTick(() => {
          this.SET_ACTIVE_DATE(String(new Date().getTime()))
          this.addCachedView({ tab: { path: path, title: meta.title, name: name } })
        });
      });
    },
    // 关闭当前tab
    closeSelectedTab(tab) {
      const currentTab = tab || this.getCurrentTab();
      this.delView({ tab: currentTab, centerId: this.defaultCenterId }).then(({ visitedViews }) => {
        if (this.isActiveTab(currentTab)) {
          this.toLastView(visitedViews);
        }
      });
    },
    // 关闭其他
    closeOthersTabs() {
      const tab = this.getCurrentTab();
      this.$router.push(tab.path);
      this.delOthersViews({ tab, centerId: this.defaultCenterId }).then(() => {
        this.moveToCurrentTab();
      });
    },
    // 关闭所有
    closeAllTabs() {
      const tab = this.getCurrentTab();
      this.delAllViews(this.defaultCenterId).then(({ visitedViews }) => {
        if (this.affixTabs.some(affixTab => affixTab.path === tab.path)) {
          return;
        }
        this.toLastView(visitedViews);
      });
    },
    isActiveTab(tab) {
      const { path } = this.$route;
      let currPath = path;
      if (/\/$/.test(currPath)) {
        currPath = currPath.slice(0, currPath.length - 1);
      }
      return tab.path === currPath;
    },
    getCurrentTab() {
      const visitedViews = (this.centerViews[this.defaultCenterId]
        && this.centerViews[this.defaultCenterId].visitedViews) || [];
      for (let i = 0; i < visitedViews.length; i += 1) {
        const tab = visitedViews[i];
        if (tab.path === this.$route.path) {
          return tab;
        }
      }
      const { fullPath: path, name, meta: { title } = {} } = this.$route;
      return {
        path, name, title
      };
    },
    // 切换到最后一个tab
    toLastView(visitedViews) {
      const latestView = visitedViews.slice(-1)[0];
      if (latestView) {
        this.$router.push(latestView.path);
      } else {
        this.$router.push({ name: 'Home' });
      }
    },
    // 移动到当前路由标签
    moveToCurrentTab() {
      const tabs = this.$refs.tab;
      this.$nextTick(() => {
        if (!tabs) {
          this.$router.push('/home')
          return;
        }
        const tabsLen = tabs.length;
        for (let i = 0; i < tabsLen; i += 1) {
          const tab = tabs[i];
          if (tab.to.path === this.$route.path) {
            this.$refs.scrollPane.moveToTarget(tab);
            break;
          }
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.tabs-view-container {
  height: 56px;
  width: 100%;
  background: black;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  .tabs-control {
    height: 56px;
    min-width: 54px;
    text-align: center;
    line-height: 56px;
    display: inline-block;
    font-size: 18px;
    cursor: pointer;
    text-decoration: none;
    background: #F2F6FC;
  }
  .tabs-control + .tabs-control {
    border-left: 1px solid #dcdfe6;
  }
  .tabs-view-wrapper {
    border-left: 1px solid #dcdfe6;
    border-right: 1px solid #dcdfe6;
    .tabs-view-item {
      display: inline-block;
      position: relative;
      cursor: pointer;
      height: 56px;
      line-height: 56px;
      padding: 0 13px !important;
      font-size: 16px;
      user-select: none;
      background: #F2F6FC;
      color: #409eff;
      &.active {
        background-color: #dcdfe6;
        color: #f56c6c;
      }
      &.noPadding {
        padding: 0;
      }
    }
  }
}
</style>

<style lang="scss">
.tabs-view-wrapper {
  .tabs-view-item {
    .el-icon-close {
      width: 16px;
      height: 16px;
      vertical-align: -1px;
      border-radius: 50%;
      text-align: center;
      transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
      transform-origin: 100% 50%;
      &:before {
        transform: scale(0.6);
        display: inline-block;
      }
      &:hover {
        background-color: pink;
        color: red;
      }
    }
  }
}
</style>
